#encoding=utf8
import MySQLdb
class MysqlHelper():
    def __init__(self, host,port,db,user,passwd,charset='utf8'):
        self.host = host
        self.port = port
        self.db   = db
        self.user = user
        self.passwd = passwd
        self.charset = charset

    #建立数据库链接
    def connect(self):
        self.conn = MySQLdb.connect(host = self.host, port = self.port, db = self.db, user = self.user, passwd = self.passwd, charset = self.charset)
        self.cursor = self.conn.cursor()

    #关闭数据库链接
    def close(self):
        self.cursor.close()
        self.conn.close()

    #获取一条表单数据
    def get_one(self,sql,params=()):
        result = None
        try:
            self.connect()
            self.cursor.execute(sql, params)
            result = self.cursor.fetchone()
            self.close()
        except Exception, e:
            print e.message
        return result

    #获取表单里所有的数据
    def get_all(self,sql,params=()):
        list = ()
        try:
            self.connect()
            self.cursor.execute(sql,params)
            list = self.cursor.fetchall()
            self.close()
        except Exception, e:
            print e.message
        return list

    #插入表单操作
    def insert(self,sql,params=()):
        return self.__edit(sql,params)

    #表单更新数据
    def update(self,sql,params=()):
        return self.__edit(sql,params)
    #删除一个表单数据
    def delete(self,sql,params=()):
        return self.__edit(sql,params)

    #表单操作函数
    def __edit(self,sql,params=()):
        count = 0
        try:
            self.connect()
            count = self.cursor.execute(sql,params)
            self.conn.commit()
            self.close()
        except Exception, e:
            print e.message
        return count
